/**
 * Created by John on 2016/7/13.
 */
var MongoClient = require('mongodb').MongoClient;
var mongo = new MongoClient();

mongo.connect('mongodb://localhost/', function (err, db) {
    var myDB = db.db('BeginningMongoDB');
    myDB.collection('word_stats', function (err, collection) {
        over12(collection);
        startingABC(collection);
        startEndVowels(collection);
        over6Vowels(collection);
        nonAlphaCharacters(collection);
        close(myDB);
    });
});

function over12(collection) {
    var query = {size: {$gt: 12}};
    var cursor = collection.find(query);
    displayCurosr(cursor, 'Words with more than 12 characters:');
}

function startingABC(collection) {
    var query = {first: {$in: ['a', 'b', 'c']}};
    var cursor = collection.find(query);
    displayCurosr(cursor, 'Word string with A, B or C:');
}

function startEndVowels(collection) {
    var vowels = ['a', 'e', 'i', 'o', 'u']
    var query = {
        $and: [
            {first: {$in: vowels}},
            {last: {$in: vowels}}
        ]
    };
    var cursor = collection.find(query);
    displayCurosr(cursor, 'Words starting and ending with a vowel:');
}

function over6Vowels(collection) {
    var query = {'stats.vowels': {$gt: 5}};
    var cursor = collection.find(query);
    displayCurosr(cursor, 'Words with more than 5 vowels:');
}

function nonAlphaCharacters(collection) {
    var query = {
        charsets: {
            $elemMatch: {
                $and: [
                    {type: 'other'},
                    {chars: {$size: 1}}
                ]
            }
        }
    };
    var cursor = collection.find(query);
    displayCurosr(cursor, 'Words with 1 non-alphabet characters:');
}

function close(myDB) {
    setTimeout(function () {
        myDB.close();
    }, 5000);
}

function displayCurosr(cursor, msg) {
    cursor.toArray(function (err, items) {
        var wordStr = '';
        for (var i in items) {
            wordStr += items[i].word + ',';
        }
        if (wordStr.length > 23) {
            wordStr = wordStr.slice(0, 23) + '...';
        }
        console.log(msg);
        console.log(wordStr);
        console.log();
    });
}